package so.ifl.commons.tools.pinter.impl;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;

import so.ifl.commons.tools.DoradoSystemUtils;
import so.ifl.commons.tools.StringHelper;
import so.ifl.commons.tools.except.SessionTimeOutException;
import so.ifl.commons.tools.pinter.Iprinter;
import so.ifl.servcie.CompanyService;
import so.ifl.servcie.OfficeService;
import so.ifl.servcie.StudentService;
import so.ifl.vo.AccountVo;
import so.ifl.vo.CompanyVo;
import so.ifl.vo.ExamBookingDetailVo;
import so.ifl.vo.OfficeVo;
import so.ifl.vo.StudentVo;

/**
 *create by aaron.lu
 *create at 2012-2-26 上午11:06:33
 *<mailto: atyuan.lu@gmail.com>
 **/
public class ResultBillPrinter implements Iprinter {

	Logger logger_ = LoggerFactory.getLogger(this.getClass());
	
	private String LIST_ = "list";
	private String COMPANY = "COMPANY";
	
	@Override
	public void print(Map<String, Object> data, HttpServletResponse response, HttpServletRequest request) throws Exception {
		logger_.debug("param:" + data);
		List<StudentVo> list = (List<StudentVo>)data.get(LIST_);
		OfficeVo officeVo = (OfficeVo)data.get(COMPANY);
 		
		
		if (null != list && list.size() > 0 && null != officeVo) {
			StudentVo studentVo = list.get(0);
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();// 用于存储每页生成PDF流
			String servletPath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() +request.getContextPath();
			String model_path = servletPath + "/templates/result_bill.pdf";
			PdfReader reader = new PdfReader(model_path);
			BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
			
			PdfStamper pdfStamper = new PdfStamper(reader, baos);			
			AcroFields form = pdfStamper.getAcroFields(); 
			form.addSubstitutionFont(baseFontChinese);
			
			form.setField("studentName", studentVo.getStudentName());
			form.setField("officeName", studentVo.getOfficeName());
			String studentSex = null != studentVo.getStudentSex() && studentVo.getStudentSex().intValue() == 1 ? "男":"女";
			form.setField("studentSex", studentSex);
			//form.setField("companyName", officeVo.getOfficeNote());
			String officeNote = officeVo.getOfficeNote();
			
			if (StringHelper.isNotEmpty(officeNote) && officeNote.equals("港龙驾校")) {
				form.setField("companyName", "中山市港龙驾驶员培训服务有限公司");
			}else if (StringHelper.isNotEmpty(officeNote) && officeNote.equals("中驾驾校")) {
				form.setField("companyName", "中山市中驾培训服务有限公司");
			}else{
				form.setField("companyName", officeVo.getOfficeNote());
			}
			
			//form.setField("studentCertificateType", studentVo.getStudentCertificateType());
			
			if (studentVo.getStudentCertificateType().equals("sl")) {
				form.setField("studentCertificateType", "居民身份证");
			}else if(studentVo.getStudentCertificateType().equals("sj")){
				form.setField("studentCertificateType", "居民身份证");
			}else{
				form.setField("studentCertificateType", studentVo.getStudentCertificateType());
			}
			String studentCertificateNumber = studentVo.getStudentCertificateNumber();
			for (int i = 0; i < studentCertificateNumber.length(); i++) {
				if (i < 18) {
					form.setField("studentCertificateNumber" + i, studentCertificateNumber.substring(i, i + 1));
				}
				
			}

			String  studentApplyType = studentVo.getStudentApplyType();
			
			if (StringHelper.isNotEmpty(studentApplyType) && studentApplyType.equals("初学")) {
				form.setField("studentApplyType1", "√");
			}else if(StringHelper.isNotEmpty(studentApplyType) && studentApplyType.equals("增驾")){
				form.setField("studentApplyType2", "√");
			}
			
			form.setField("studentApplyDriveType", studentVo.getStudentApplyDriveType());
			form.setField("studentDriveTypeNow", studentVo.getStudentDriveTypeNow());
			
			pdfStamper.setFormFlattening(true); // 千万不漏了这句啊, */
			pdfStamper.close();
			
			ServletOutputStream out = response.getOutputStream();			
			response.setContentType("application/pdf");
			
			baos.writeTo(out);
			out.flush();						
			
			baos.close();
		}

	}

	@Override
	public Map<String, Object> getData(HttpServletRequest request)throws Exception {
		
		
		String studentId = request.getParameter("studentId");
		Map<String, Object> result = new HashMap<String, Object>();
		
		if (StringHelper.isNotEmpty(studentId)) {
		
			
			ServletContext servletContext = request.getSession().getServletContext();		
			ApplicationContext appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
			
			StudentService studentService = (StudentService)appctx.getBean("studentService");
			OfficeService officeService  = (OfficeService)appctx.getBean("officeService");
			
			Map<String, Object> params = new HashMap<String, Object>();
			params.put("student_id_", studentId);
 			
			List<StudentVo> list = studentService.queryStudentWithParamAndPagination(params, 0, 1);
			
			result.put(LIST_, list);
			
			
			AccountVo accountVo = DoradoSystemUtils.getCurrentUser(request);
			
			if (null == accountVo) {
				throw new SessionTimeOutException("登录超时...");
			}
		
			
			List<OfficeVo> officeVos = officeService.queryOfficeByStudent(params);
			
			if (null != officeVos && officeVos.size() > 0) {
				result.put(COMPANY, officeVos.get(0));
			}
			
		}		

		return result;
	}

}
